<?php

// TODO: create a gallery model to handle the collection and a model for each image
// TODO: sort the tags before exporting them

class MullisgalleryController extends GalleryController {

    // show()
    // displays a list of the latest blog posts
    //
    public function show( $vars=NULL ) {
        $page = $this->getPage();

        $json = f::read('data/gallery.json');
        $gallery = json_decode($json);
        $images = get_object_vars($gallery->images);
        uasort($images, array('MullisgalleryController','sortByDate'));

        // extract the used tags for drilldown
        $tags = array();
        foreach($images as $image) {
            $tags = array_merge($tags, $image->tags);
        }
        $tags = array_unique($tags);

        $page->set( 'images', $images );
        $page->set( 'tags', $tags);
    }

    // image()
    //
    public function image( $vars=NULL ) {
        $page = $this->getPage();

        $id = a::get($vars, 0);
        $json = f::read('data/gallery.json');
        $gallery = json_decode($json);
        $image = $gallery->images->$id;

        $page->set( 'image', $image );
    }

    public function tag($vars=NULL) {
        $page = $this->getPage();

        $tag = a::get($vars, 0);
        $json = f::read('data/gallery.json');
        $gallery = json_decode($json);

        $collection = array();
        foreach($gallery->images as $key => $image) {
            if(a::contains($image->tags, $tag)) {
                $collection[$key] = $image;
            }
        }

        uasort($collection, array('MullisgalleryController','sortByDate'));

        $page->set('collection', $tag);
        $page->set('gallery', $collection);
    }

    static function sortByDate($a, $b) {
        $aDate = strtotime($a->date);
        $bDate = strtotime($b->date);
        if($aDate == $bDate) return 0;
        return ($aDate > $bDate) ? +1 : -1;
    }
}

